package mornd.test3.web;

import lombok.ToString;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.ServletRequestParameterPropertyValues;

import java.util.Date;

/**
 * @author: mornd
 * @dateTime: 2023/5/7 - 23:06
 * web 环境下参数与对象绑定
 */
public class WebDataBinderDemo {
    public static void main(String[] args) {
        User user = new User();
        ServletRequestDataBinder dataBinder = new ServletRequestDataBinder(user);
        // 不使用 setxx 方法赋值，直接通过属性赋值
        dataBinder.initDirectFieldAccess();
        MockHttpServletRequest request = new MockHttpServletRequest();
        request.setParameter("id",  "1003");
        request.setParameter("name",  "alice");
        request.setParameter("birthday",  "1998/1/1");
        request.setParameter("age",  "23");
        request.setParameter("address.name",  "广州");

        ServletRequestParameterPropertyValues propertyValues = new ServletRequestParameterPropertyValues(request);

        dataBinder.bind(propertyValues);
        System.out.println(user);
    }

    //@Setter
    @ToString
    static class User {
        private Integer id;
        private Address address;
        private String name;
        private Date birthday;
        private int age;
    }

    @ToString
    static class Address {
        private  String name;
    }
}
